<?php

namespace app\admin\controller\user;

use app\admin\validate\FundsRecord;
use app\api\controller\Funds;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\Agent;
use app\common\model\AppConfig;
use app\common\model\UserLevelRecord;
use think\Db;
use think\Exception;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;

    /**
     * User模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
	        
            $total = $this->model
                    ->with(['group','recommend'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
	                ->with(['group','recommend'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $k => $v)
            {
                $v->hidden(['password', 'salt']);
            }
	        $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->with('recommend')->find($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
         if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $row = Db::name('user')
                        ->where(['username' => $params['username'], 'id' => ['neq', $ids]])
                        ->find();
                    if($row) {
                        $this->error('用户名已经存在 ');
                    }


                    if($params['recommend_mobile']) {
                        $recommend = Db::name('user')
                            ->where(['mobile' => $params['recommend_mobile']])
                            ->find();
                        if(!$recommend) {
                            $this->error('推荐人不存在');
                        }

                        $params['recommend_id'] = $recommend['id'];
                    }

                    unset($params['recommend_mobile']);
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $this->model->save($params,['id' => $ids]);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
	
	/**
	 * 升级
	 */
	public function upLevel($ids = NULL)
	{
		$row = $this->model->get($ids);
		if (!$row){
			$this->error(__('No Results were found'));
		}
		
		$model = new \app\admin\model\User();
		if($row['level'] == $model::LEVEL_OPERATIONS) {
			$this->error('已经是最高级别');
		}
		
		$recordModel = new UserLevelRecord();
		$model->startTrans();
		try {
			$recordRes = $recordModel->addRecord($row, $this->auth->id,'后台手动升级');
			if(!$recordRes) {
				throw new Exception('添加升级记录出错');
			}
			
			$res = $model->where(['id' => $row['id']])->setInc('level');
			if(!$res) {
				throw new Exception('更改等级出错');
			}
			
			$model->commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			$model->rollback();
			$this->error('操作出错:'.$e->getMessage());
		}
		
	}
	
	/**
	 * 编辑
	 */
	public function recharge($ids = NULL)
	{
		$row = $this->model->find($ids);
		
		$fundsModel = new \app\common\model\FundsRecord();
		$accountList = $fundsModel::$_account_type;
		if (!$row) {
			$this->error(__('No Results were found'));
		}

        $account_field_trans = array_flip($fundsModel::$_account_field);
        $video_index = $account_field_trans['video_time'];
        unset($accountList[$video_index]);


		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				if(!$params['type'] || !in_array($params['type'], array_keys($accountList))) {
					$this->error('请选择充值类型');
				}
				
				if(!$params['amount']) {
					$this->error('请填写充值金额');
				}
				
				
				$fiels = $fundsModel::$_account_field;
				Db::startTrans();
				try {
					
					//添加或减少用户帐户
					$userRes = Db::name('user')
						->where(['id' => $ids])
						->setInc($fiels[$params['type']], $params['amount']);
					if(!$userRes) {
						throw new Exception('更改会员资金出错');
					}
					
					if($params['amount'] > 0) {
						$opeType = $fundsModel::OPE_TYPE_PLUS;
					} else {
						$opeType = $fundsModel::OPE_TYPE_LESS;
					}
					
					$logRes = $fundsModel->addRecord($row['id'], abs($params['amount']), $row[$fiels[$params['type']]], $params['type'], $opeType, $fundsModel::TYPE_ADMIN_OPERATE, '', $params['remark']);
					if(!$logRes) {
						throw new Exception('添加资金记录出错');
					}
					
					if($params['type'] == $fundsModel::ACCOUNT_TYPE_PHONE) {
						if($params['days'] == 0) {
							throw new Exception('请输入话费有效期');
						}
						
						if($params['days'] > 0) {
							$time = strtotime('+'.$params['days'].' days', $row['phone_time'] > time() ? $row['phone_time'] : time());
						} else {
							$time = strtotime($params['days'].' days', $row['phone_time'] > time() ? $row['phone_time'] : time());
						}
						
						$dayRes = Db::name('user')
							->where(['id' => $row['id']])
							->setField('phone_time', $time);
						if(!$dayRes) {
							throw new Exception('更改话费有效期出错');
						}
					}

                    if($params['type'] == $fundsModel::ACCOUNT_TYPE_VIDEO){
                        $beforeDays = 0;
                        if ($row['video_time'] > time()) {
                            $beforeDays = ceil(($row['video_time']-time())/(24*60*60));
                        }
                        if ($beforeDays == 0) {
                            $ts = time()+$params['days'] * 24*3600;
                        }
                        else
                        {
                            $ts = $row['video_time'] + $params['days'] *24*3600;
                        }
                        $dayRes = Db::name('user')
                            ->where(['id' => $row['id']])
                            ->setField('video_time', $ts);
                        if(!$dayRes) {
                            throw new Exception('更改影视有效期出错');
                        }
                    }
					
					Db::commit();
					$this->success('充值成功');
				} catch (\think\exception\PDOException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		return $this->view->fetch('recharge', [
			'accountList' => $accountList,
			'user' => $row
		]);
	}
	
	
	/**
	 * vip等级设置
	 */
	public function vip($ids){
		$row = $this->model->find($ids);
		if($this->request->isAjax()) {
			$level = $this->request->post('level');
			if($level == $row['level']) {
				$this->success();
			}
			
			Db::startTrans();
			try {
				//更改会员等级
				$userRes = $this->model->where(['id' => $ids])->update(['level' => $level]);
				if(!$userRes) {
					throw new Exception('更改等级出错');
				}
				
				$logModel = new UserLevelRecord();
				$logRes = $logModel->addRecord($row['id'], $row['level'], $level, $this->auth->id, '后台更改等级');
				if(!$logRes) {
					throw new Exception('记录级别变更记录出错');
				}
				
				Db::commit();
				$this->success();
			} catch (Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}
		}
		return $this->fetch('vip', [
			'row' => $row,
			'vipList' => [
				0 => '普通用户',
				1 => '初级VIP',
				2 => '高级VIP'
			]
		]);
	}
	
	/**
	 * 修改密码
	 */
	public function password($ids){
		$row = $this->model->find($ids);
		if($this->request->isAjax()) {
			$type = $this->request->post('type');
			$password = $this->request->post('password');
			!$password && $this->error('密码不能为空');
			
			if(strlen($password) < 6) {
				$this->error('密码最少6位');
			}
			
			if($type == 2 && !preg_match('/^\d{6}$/', $password)) {
				$this->error('支付密码只能是6位数字');
			}
			
			$password = Auth::instance()->getEncryptPassword($password, $row['salt']);
			if($type == 1) {
				$userRes = $this->model->where(['id' => $ids])->update(['password' => $password]);
			} else {
				$userRes = $this->model->where(['id' => $ids])->update(['pay_password' => $password]);
			}
			if($userRes === false) {
				$this->error('更改密码出错');
			} else {
				$this->success();
			}
		}
		return $this->fetch('password', [
			'row' => $row,
			'typeList' => [
				1 => '登录密码',
				2 => '支付密码'
			]
		]);
	}
	
	/**
	 * 查看信息
	 */
	public function info($ids){
		$row = $this->model->find($ids);
		return $this->fetch('info', [
			'row' => $row,
		]);
	}
	
	/**
	 * 更改上级
	 */
	public function changeRecommend($ids){
		$row = $this->model->find($ids);
		if($row['recommend_count'] > 0) {
			$this->error('该用户已经推荐了用户，不能修改上级');
		}
		
		if($this->request->isAjax()) {
			$mobile = $this->request->post('mobile');
			
			
			$recommend = Db::name('user')->alias('u')
				->join('agent a', 'u.id = a.user_id', 'left')
				->where(['u.mobile' => $mobile, 'u.status' => 1])
				->field('u.id, u.parent_path, u.agent_user_id, a.id as agent_id, u.level')
				->find();
			if (!$recommend) {
				$this->error('推荐人不存在');
			}
			
			if($recommend['level'] == 0) {
				$this->error('该用户没有推荐权限');
			}
			
			$userData['recommend_id'] = $recommend['id'];
			
			//如果推荐人是代理商，那么新用户代理商就是推荐人，否则如果推荐人有归属代理，那么新用户和推荐人同一个代理
			if($recommend['agent_id']) {
				$userData['agent_user_id'] = $recommend['id'];
			} elseif ($recommend['agent_user_id']) {
				$userData['agent_user_id'] = $recommend['agent_user_id'];
			}
			
			//生成所有上级路径
			if($recommend['parent_path']){
				$userData['parent_path'] = $recommend['parent_path'].','.$recommend['id'];
			} else {
				$userData['parent_path'] = $recommend['id'];
			}
			
			Db::startTrans();
			try {
				//更改会员推荐人和推荐人路径
				$userRes = Db::name('user')->where(['id' => $ids])->update($userData);
				if(!$userRes) {
					throw new Exception('更改用户信息出错');
				}
				
				//更改原来推荐人的推荐数量
				$oldRes = Db::name('user')->where(['id' => $row['recommend_id']])
					->setDec('recommend_count');
				if(!$oldRes) {
					throw new Exception('减少原来推荐人推荐数量出错');
				}
				
				//更改新推荐人的推荐数量
				$newRes = Db::name('user')->where(['id' => $recommend['id']])
					->setInc('recommend_count');
				if(!$newRes) {
					throw new Exception('添加新推荐人推荐数量出错');
				}
				
				
				Db::commit();
				$this->success();
			} catch (Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}
		}
		return $this->fetch('changeRecommend', [
			'row' => $row,
		]);
	}
	
	/**
	 * 更改归属代理
	 */
	public function changeAgent($ids){
		$row = $this->model->find($ids);
		if($this->request->isAjax()) {
			$mobile = $this->request->post('mobile');
			$agent = Db::name('agent')->alias('a')
				->join('user u', 'a.user_id = u.id', 'left')
				->where(['u.mobile' => $mobile, 'a.status' => Agent::STATUS_Y])
				->field('a.*')
				->find();
			!$agent && $this->error('代理商不存在');
			
			$userRes = $this->model->where(['id' => $ids])->update(['agent_user_id' => $agent['user_id']]);
			if(!$userRes) {
				$this->error('更改出错');
			}
			$this->success();
			
		}
		return $this->fetch('changeRecommend', [
			'row' => $row,
		]);
	}
}
